//会员卡
(function() {
	var config = require("../_include/config");
	var db = require("../db/index");
	var md5 = require("../_include/md5");
	var helper = require("../_include/helper");
	var db_table_name = config.dbname.cardFactory;
	var db_id_prefix = config.dbIdPrefix.cardFactory;
	//构造函数
	var _con = function(info) {
		if (!info) {
			throwCusError("参数错误，会员卡信息不可为空");
		}
		this._id = db_id_prefix + (+new Date).toString(36) + Math.random().toString(36).substr(2);
		this.bus_id = info.bus_id;

		this.info = {};
		this.setInfo(info);

		//已经发行的会员卡
		this.card_list = [];

		//会员卡对应的商品集合
		this.goods_list = [];

		//BUFF
		var buff = new BuffCon({
			name: this.info.name,
			code_id: "会员卡",
			config: {
				card_factory_id: this._id
			}
		});
		this.buff_id = buff._id;

		this.create_time = +new Date;
		db.insert(db_table_name, this);
		console.log("生成了一个会员卡包：", this._id);
	};

	module.exports = _con;

	//技能
	_con.prototype = require("./skill");
	_con.STATE = {
		可用: 1,
		冻结: 2,
	};
	_con.TYPE = {
		打折: 1,
		满减: 2,
		现金抵用: 3
	};


	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		if (result) {
			result.__proto__ = _con.prototype;
		}
		return result;
	};
	//生成默认的描述信息
	_con.getIntro = function(instance) {
		var result = "";
		var config = instance.info.config;
		switch (instance.info.type) {
			case _con.TYPE.打折:
				if (config.is_grads) {

				} else {
					result += "折扣：{0} 折\n".format(config.discount);
				}
				break;
			case _con.TYPE.满减:
				if (config.is_grads) {

				} else {
					result += "满 {0} 减 {1}\n".format(config.full_cash, config.cut_cash);
				}
				break;
			case _con.TYPE.现金抵用:
				if (config.is_grads) {

				} else {
					result += "抵用金额：{0}\n".format(config.directly_cut_cash);
				}
				break;
		}
		//关于有效期
		if (instance.info.diedline == Number.MAX_VALUE) {
			result += "永久有效\n";
		} else {
			if (instance.info.diedline > +new Date) {
				result += "有效期至：{0}\n".format(new Date.format("yyyy年MM月dd号 HH:mm"));
			} else {
				result += "已过期\n";
			}
		}
		return result;
	}
	_con.canUseForAch = function(card_factory, ach) {
		console.log(ach)
		var card_factory_info = card_factory.info;
		if (card_factory.bus_id !== ach.info.bus_id) {
			return false;
		}

		var res = false;
		res = ach.info.goods_info.every(function(goods_info) {
			//普通商品可以直接使用
			if (!goods_info.goods.card_factory_list || !goods_info.goods.card_factory_list.length) {
				return true
			} else {
				//特殊商品，有会员专区指定标识的也可使用
				//如果不是通过会员专区下单(return false)，也就是这个商品订单下单方式不是官方的，不然不会出现在订单中，这时候，整个订单都无法享有优惠。
				return goods_info.goods.card_factory_list.some(function(card_factory_id) {
					return card_factory_id == card_factory._id
				});
			}
		});

		return res;
	};
	_con.cardId_has_user = function(card_id, user_id) {
		return card_id.indexOf("|U:" + user_id) > -1;
	}

	var BuffCon = require("../buff/_con");

}());